package cn.cf.kxx;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.cf.kxx.data.DataSharedPreferences;
import cn.cf.kxx.fram.OnActivityInteractionListener;
import cn.cf.kxx.fram.OnFragmentInteractionListener;
import cn.cf.kxx.model.Device;
import cn.cf.kxx.model.Group;
import cn.cf.kxx.model.Valve;
import cn.cf.kxx.model.comm.MobileMsg;
import cn.cf.kxx.model.comm.MqMessage;
import cn.cf.kxx.model.dev.Hold;
import cn.cf.kxx.service.IMyAidlCallBack;
import cn.cf.kxx.service.ISerialAidlInterface;
import cn.cf.kxx.tools.MQTTUtils;
import cn.cf.kxx.tools.OkHttpUtils;
import cn.cf.kxx.tools.Tools;
import cn.cf.kxx.tools.UpgradeManager;
import cn.cf.kxx.ui.main.SectionsPagerAdapter;
import cn.cf.kxx.databinding.ActivityMain2Binding;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity2 extends AppCompatActivity implements ViewPager.OnPageChangeListener, OnActivityInteractionListener, View.OnClickListener {

    private ActivityMain2Binding binding;
    List<Fragment> fragmentList;

    DataSharedPreferences sharedPreferences;

    private Hold hold;

    FloatingActionButton fab;

    ViewPager viewPager;

    MQTTUtils mqttUtils;

    String devBh;

    NetworkReceiver networkReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding = ActivityMain2Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        fab = binding.fab;
        fab.setBackgroundTintList(ColorStateList.valueOf(Color.YELLOW));
        binding.fab.setOnClickListener(this);

        sharedPreferences = DataSharedPreferences.getInstance();
        hold = sharedPreferences.getHold(this);

        if(TextUtils.isEmpty(sharedPreferences.getDd(this))){
            // 生成哈希值
            int hash = Tools.getDeviceId(this).hashCode();

            // 将哈希值转换为正数
            long positiveHash = Math.abs((long) hash);

            // 取模，确保结果为8位数字
            long result = positiveHash % 100000000;

            // 输出8位数字
            sharedPreferences.addDd(this, Tools.getDevBh(String.format("%08d", result)));


            //缓存读出来
            String content = sharedPreferences.getGuide(this);
            Type listType = new TypeToken<ArrayList<Valve>>() {}.getType();
            valves = Tools.gson.fromJson(content, listType);
            if(valves.size() == 0){
                Valve valve;
                for(int i = 1;i < 65;i++){
                    valve = new Valve();
                    valve.setType(1);//无线网关
//                valDevice.setParentId(device.getParentId());
                    valve.setDevBh(devBh);
//                valve.setCreateDate(new Date());
                    valve.setFmBh(i);
                    valve.setLatitude("0.0");
                    valve.setLongitude("0.0");
                    valve.setVoltage(0f);
                    valve.setPulseA(0);
                    valve.setPulseB(0);
//                valve.setModifyDate(new Date());
                    valve.setName(String.valueOf(i));
                    valve.setValveA("0");
                    valve.setValveB("0");
                    valve.setStatus(0);
                    valve.setExtVoltage1(0f);
                    valve.setExtVoltage2(0f);
                    valve.setHumidity(0f);
                    valve.setTemper(0f);
                    valves.add(valve);
                }
                sharedPreferences.addGuide(this,Tools.gson.toJson(valves));
            }

            //缓存读出来
            content = sharedPreferences.getGroup(this);
            listType = new TypeToken<ArrayList<Group>>() {}.getType();
            ArrayList<Group> groups = Tools.gson.fromJson(content, listType);
            if(groups.size() == 0){
                Group group;
                for(int i = 1;i < 51;i++){
                    group = new Group();
//                group.setParentId(device.getParentId());
                    group.setDevBh(devBh);
                    group.setZbh((short) i);
                    group.setName("默认" + i);
                    group.setRemarks("无");
                    group.setStatus(0);
                    group.setContent("");
                    group.setCreateDate(new Date());
                    groups.add(group);
                }
                sharedPreferences.addGroup(this, Tools.gson.toJson(groups));
            }
        }

        fragmentList = new ArrayList<>();

        Bundle args = new Bundle();
        devBh = sharedPreferences.getDd(this);
        args.putString("devBh",devBh);
        fragmentList.add(MainActivity.newInstance(args));
        fragmentList.add(PumpActivity.newInstance(args));
        fragmentList.add(FertilizerActivity.newInstance(args));
        fragmentList.add(ExePlanActivity.newInstance(args));
        fragmentList.add(IrrigateActivity.newInstance(args));
        fragmentList.add(ValveActivity.newInstance(args));
        fragmentList.add(PoliceActivity.newInstance(args));
        fragmentList.add(SettingActivity.newInstance(args));

        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());

        sectionsPagerAdapter.setFragmentList(fragmentList);

        viewPager = binding.viewPager;
        viewPager.setAdapter(sectionsPagerAdapter);

        viewPager.addOnPageChangeListener(this);

        TabLayout tabs = binding.tabs;
        tabs.setupWithViewPager(viewPager);

        FloatingActionButton fab = binding.fab;

        fab.setOnClickListener(this);

        initService();

        networkReceiver = new NetworkReceiver();

        registerReceiver(networkReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
//        UpgradeManager upgradeManager = new UpgradeManager(this);
    }

    public class NetworkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
            // 特殊注意：如果if条件生效，那么证明当前是有连接wifi或移动网络的，如果有业务逻辑最好把esle场景酌情考虑进去！
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                //获取联网状态的NetworkInfo对象
                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (info != null) {
                    //如果当前的网络连接成功并且网络连接可用
                    if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
                        Log.e("nyz", Tools.getConnectionType(info.getType()) + "已连接");
                        switch (info.getType()) {
                            case ConnectivityManager.TYPE_WIFI:
                                Log.e("nyz", "wifi网络" + "已连接");
                                mqttUtils.connecting();

                                break;
                            case ConnectivityManager.TYPE_MOBILE:
                                Log.e("nyz", "数据网络" + "已连接");
                                mqttUtils.connecting();
                                break;
                        }
                    } else {
                        Log.e("nyz", Tools.getConnectionType(info.getType()) + "已断开");
                    }
                } else {
                    Log.e("nyz", "无网络");
                }
            }
        }
    }

    Timer timer;

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            try {
            byte[] bytes = (byte[]) msg.obj;
            switch (msg.what){
                case 0x03://保持

                    hold.setBaud(((bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF)) == 0 ? 115200 : 9600);
                    hold.setVersion(((bytes[4] & 0xFF) << 8 | (bytes[5] & 0xFF)));
                    hold.setAd1((short) ((bytes[6] & 0xFF) << 8 | (bytes[7] & 0xFF)));
                    hold.setAd2((short) ((bytes[8] & 0xFF) << 8 | (bytes[9] & 0xFF)));
                    hold.setId1((short) ((bytes[10] & 0xFF) << 8 | (bytes[11] & 0xFF)));
                    hold.setId2((short) ((bytes[12] & 0xFF) << 8 | (bytes[13] & 0xFF)));
                    hold.setXd1((short) ((bytes[14] & 0xFF) << 8 | (bytes[15] & 0xFF)));
                    hold.setXd2((short) ((bytes[16] & 0xFF) << 8 | (bytes[17] & 0xFF)));
                    hold.setKx1((short) ((bytes[18] & 0xFF) << 8 | (bytes[19] & 0xFF)));
                    hold.setKx2((short) ((bytes[20] & 0xFF) << 8 | (bytes[21] & 0xFF)));
                    sharedPreferences.addHold(MainActivity2.this,hold);
                    if(fragmentList.get(selectIndex) instanceof SettingActivity){
                        ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashValues(hold);
                    }
                    break;
                case 0x01:
                        if((bytes[0] & 1) == 1){
                            //读主站区域
                            iSerialAidlInterface.sendMessage(4,0,10,null);
                            iSerialAidlInterface.sendMessage(5,0,0,new byte[]{0});
                        }
                        if((bytes[0] >> 1  & 1) == 1){
                            //读从站返回区域
                            iSerialAidlInterface.sendMessage(4,10,14,null);//读取缓冲区的阀门
                            iSerialAidlInterface.sendMessage(5,1,0,new byte[]{0});//更改状态
                        }
                        if((bytes[0] >> 2 & 1) == 1){
                            //跑水刷新全部
                            iSerialAidlInterface.sendMessage(4,24,32,null);
                            iSerialAidlInterface.sendMessage(5,2,0,new byte[]{0});//更改状态
                        }
                        //更新阀门因为阀门没有反馈
                        String data = sharedPreferences.getDevice(MainActivity2.this);
                        if(!TextUtils.isEmpty(data)){
                            String status = bytes[0] >> 6 == 1 ? "on" : "off";

                            Device device = Tools.gson.fromJson(data,Device.class);
                            //变化了才上报
                            if(!status.equals(device.getWaterInjection())){
                                MqMessage mqMessage = new MqMessage();
                                mqMessage.setType(2);
                                mqMessage.setDevBh(devBh);
                                mqMessage.setData("{\"waterInjection\":\""+status+"\"}");
                                mqttUtils.publish(Tools.gson.toJson(mqMessage));
                                device.setWaterInjection(status);
                                sharedPreferences.addDevice(MainActivity2.this,Tools.gson.toJson(device));

                            }
                            //刷新页面阀门状态
                            if(fragmentList.get(selectIndex) instanceof MainActivity
                                    || fragmentList.get(selectIndex) instanceof FertilizerActivity){
                                ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashValve(bytes[0] >> 6);
                            }
                        }
                    break;
                case 0x04:
                    //判断数据的位置

                   switch (bytes.length){
                       case 20:
                           //刷新界面
                           if(fragmentList.get(selectIndex) instanceof MainActivity
                                   || fragmentList.get(selectIndex) instanceof PumpActivity
                                   || fragmentList.get(selectIndex) instanceof FertilizerActivity){
                               ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashValues(bytes);
                           }

                           data = sharedPreferences.getDevice(MainActivity2.this);
                           if(!TextUtils.isEmpty(data)){
                               Device device = Tools.gson.fromJson(data,Device.class);
                               device.setFlow(String.valueOf(Tools.IEE754Parser(Arrays.copyOfRange(bytes,0,4))));
                               device.setPressure(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,11,13))));
                               device.setFatPress(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,13,15))));
                               device.setFatFlow(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,15,17))));

                               byte di = bytes[19];
                               if((di >> 5 & 1) == 1){
                                   device.setFluidDepth(0f);
                               }else if((di >> 6 & 1) == 1){
                                   device.setFluidDepth(100f);
                               }else{
                                   device.setFluidDepth(50f);
                               }
                               MqMessage mqMessage = new MqMessage();
                               mqMessage.setType(2);
                               mqMessage.setDevBh(devBh);
                               if((di & 1) == 0){
                                   if("on".equals(device.getWaterPower())){     //变化则上传
                                       mqMessage.setData("{\"waterPower\":\"off\"}");
                                       mqttUtils.publish(Tools.gson.toJson(mqMessage));
                                   }
                                   device.setWaterPower("off");
                               }else{
                                   if("off".equals(device.getWaterPower())){
                                       mqMessage.setData("{\"waterPower\":\"on\"}");
                                       mqttUtils.publish(Tools.gson.toJson(mqMessage));
                                   }
                                   device.setWaterPower("on");
                               }

                               if((di >> 1 & 1) == 0){
                                   if("on".equals(device.getFluidPower())){
                                       mqMessage.setData("{\"fluidPower\":\"off\"}");
                                       mqttUtils.publish(Tools.gson.toJson(mqMessage));
                                   }
                                   device.setFluidPower("off");
                               }else {
                                   if("off".equals(device.getFluidPower())){
                                       mqMessage.setData("{\"fluidPower\":\"on\"}");
                                       mqttUtils.publish(Tools.gson.toJson(mqMessage));
                                   }
                                   device.setFluidPower("on");
                               }

                               if((di >> 2 & 1) == 0){
                                   if("on".equals(device.getFluidStir())){
                                       mqMessage.setData("{\"fluidStir\":\"off\"}");
                                       mqttUtils.publish(Tools.gson.toJson(mqMessage));
                                   }
                                   device.setFluidStir("off");
                               }else{
                                   if("off".equals(device.getFluidStir())){
                                       mqMessage.setData("{\"fluidStir\":\"on\"}");
                                       mqttUtils.publish(Tools.gson.toJson(mqMessage));
                                   }
                                   device.setFluidStir("on");
                               }

                               //
                               device.setWaterRunVoltage(String.valueOf(Tools.TwoByteParserBig(Arrays.copyOfRange(bytes,6,8))));
                               device.setWaterRunElect(String.valueOf(Tools.TwoByteParserBig(Arrays.copyOfRange(bytes,8,10))));
                               device.setPipPress(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,11,13))));

                               sharedPreferences.addDevice(MainActivity2.this,Tools.gson.toJson(device));
                           }
                           break;
                       case 28:
                           //刷新阀门

                           //缓存读出来
                           String content = sharedPreferences.getGuide(MainActivity2.this);
                           Type listType = new TypeToken<ArrayList<Valve>>() {}.getType();
                           List<Valve> valves = Tools.gson.fromJson(content, listType);
                           int index = bytes[1] - 1;
                           Valve valve = valves.get(index);
                           //开关状态
                           //低位是A
                           valve.setValveA(String.valueOf(bytes[3]));
                           //高位是B
                           valve.setValveB(String.valueOf(bytes[2]));
                           //压力值
                           valve.setExtVoltage1(Tools.TwoByteParserBig(ArrayUtils.subarray(bytes,4,6)));
                           valve.setExtVoltage2(Tools.TwoByteParserBig(ArrayUtils.subarray(bytes,6,8)));
                           //脉冲值
                           valve.setPulseA(com.serotonin.modbus4j.sero.util.ArrayUtils.byteRangeValue(bytes,8,2));
                           valve.setPulseB(com.serotonin.modbus4j.sero.util.ArrayUtils.byteRangeValue(bytes,10,2));
                           //过水状态
                            if(bytes[12] == 1){
                                //高位是B
                               valve.setValveB("2");
                            }
                           if(bytes[13] == 1){
                                //低位是A
                               valve.setValveA("2");
                           }
                           //土壤溫度
                           valve.setTemper(Tools.TwoByteParserBig(ArrayUtils.subarray(bytes,14,16)));
                           //土壤湿度
                           valve.setHumidity(Tools.TwoByteParserBig(ArrayUtils.subarray(bytes,16,18)));
                            //信号强度
                           valve.setSignal(com.serotonin.modbus4j.sero.util.ArrayUtils.byteRangeValue(bytes,18,2));
                           //充电状态
                           valve.setStatus(com.serotonin.modbus4j.sero.util.ArrayUtils.byteRangeValue(bytes,20,2));
                           //外部电源电压22

                           //电池电压
                           valve.setVoltage(Tools.TwoByteParserBig(ArrayUtils.subarray(bytes,24,26)));
                           //太阳能电池电压
                           valve.setSolarVoltage(Tools.TwoByteParserBig(ArrayUtils.subarray(bytes,26,28)));

                           valves.set(index,valve);

                           sharedPreferences.addGuide(MainActivity2.this,Tools.gson.toJson(valves));

                           if(fragmentList.get(selectIndex) instanceof ValveActivity){
                               ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashValues(bytes);
                           }

                           //刷新平台
                           valves.clear();
                           valves.add(valve);
                           uploadValDevice(valves);
                           break;
                   }

                    //阀门内容需要保存到缓存中
                    break;
                case 0x05:

                    break;
                default:
                    Log.e("dong", "fun:"+msg.what + "  value:"+Tools.bytesToHex(bytes));
            }
            } catch (RemoteException e) {
            }

        }
    };

    Timer timerRegist;
    TimerTask regist;

    List<Valve> valves = new ArrayList<>();

    // MQTT监听并且接受消息
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            String str1 = new String(message.getPayload());
            String str2 = topic + ";qos:" + message.getQos() + ";retained:" + message.isRetained();
            Log.e("dong", "messageArrived:" + str1);
            Log.e("dong", str2);

            MqMessage mqMessage =  Tools.gson.fromJson(str1,MqMessage.class);
            switch (mqMessage.getType()){
                case 1://心跳 存储token
                    sharedPreferences.addUser(MainActivity2.this,mqMessage.getData().toString());
                    if("success".equals(mqMessage.getStatus())){
                        if(timer == null){
                            heart(mqMessage.getData().toString());
                        }
                    }
                    if(regist !=null){
                        regist.cancel();
                        regist = null;
                        timerRegist.cancel();
                        timerRegist = null;
                    }

                    break;
                case 2://远端控制
                    control(mqMessage);
                    break;
                case 3://召测阀门
                    String content = sharedPreferences.getGuide(MainActivity2.this);
                    Type listType = new TypeToken<ArrayList<Valve>>() {}.getType();
                    List<Valve> list = new Gson().fromJson(content, listType);
                    valves.clear();
                    valves.addAll(list);
                    uploadValDevice(valves);
                    break;
            }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            //当消息传递完成并且所有确认均已收到时调用。
            try {

                MqMessage mqMessage = Tools.gson.fromJson(String.valueOf(arg0.getMessage()),MqMessage.class);
                switch (mqMessage.getType()){
                    case 1:
                        Log.e("dong","注册发送成功");
                        if(timerRegist == null){
                            timerRegist = new Timer();
                            timerRegist.schedule(regist = new TimerTask() {
                                @Override
                                public void run() {
                                    MqMessage mqMessage = new MqMessage();
                                    mqMessage.setDevBh(devBh);
                                    mqMessage.setType(1);
                                    mqMessage.setMsg("设备注册");
                                    mqttUtils.registDevice(Tools.gson.toJson(mqMessage));
                                }
                            },10000,10000);
                        }
                        break;
                }
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void connectionLost(Throwable arg0) {
            // 失去连接，重连
            if(timer != null){
                timer.cancel();
            }
        }

    };

    private void uploadValDevice(List<Valve> valves){

        //启动轮询任务，查询所有阀门，完成后刷新后台

        OkHttpUtils.getInstane(token).httpPost(this,Tools.uploadValDevice,Tools.gson.toJson(valves),"uploadValDevice",new Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("dong","上报阀门列表失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()) {
                    Log.e("dong", "uploadValDevice" + response.code() + response.body().string());
                }
            }
        });
    }

    private void control(MqMessage mqMessage){
        try {
            JSONObject con = new JSONObject(mqMessage.getData().toString());
            if(con.has("waterPower")){
                Log.e("dong",con.getString("waterPower"));
                if("on".equals(con.getString("waterPower"))){
                    sendCommand(5,3,1,new byte[]{1});
                }else{
                    sendCommand(5,3,1,new byte[]{0});
                }
//                mqttUtils.publish(Tools.gson.toJson(mqMessage));
            }else if(con.has("fluidPower")){
                Log.e("dong",con.getString("fluidPower"));
                if("on".equals(con.getString("fluidPower"))){
                    sendCommand(5,4,1,new byte[]{1});
                }else{
                    sendCommand(5,4,1,new byte[]{0});
                }
//                mqttUtils.publish(Tools.gson.toJson(mqMessage));
            }else if(con.has("fluidStir")){
                Log.e("dong",con.getString("fluidStir"));
                if("on".equals(con.getString("fluidStir"))){
                    sendCommand(5,5,1,new byte[]{1});
                }else{
                    sendCommand(5,5,1,new byte[]{0});
                }
//                mqttUtils.publish(Tools.gson.toJson(mqMessage));
            }else if(con.has("waterInjection")){
                Log.e("dong",con.getString("waterInjection"));
                if("on".equals(con.getString("waterInjection"))){
                    sendCommand(5,6,1,new byte[]{1});
                }else{
                    sendCommand(5,6,1,new byte[]{0});
                }
//                mqttUtils.publish(Tools.gson.toJson(mqMessage));
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    private String token;

    private int refrash = 60;

    private void heart(String token){
        this.token = token;
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mqttUtils.heartBeat();
                //刷新实时数据接口
                uploadDevice();
                //
                Log.e("dong","heart...........................");
                if(refrash == 0){
                    refrash = 60;
                    try {
                        JSONObject jo = new JSONObject(sharedPreferences.getDevice(MainActivity2.this));
                        String parentId = jo.getString("parentId");
                        initfarm(parentId);
                    } catch (JSONException e) {
                        //
                    }
                }else{
                    refrash -= 1;
                }
            }
        },3000,60000);
        //到后台拉取设备信息
        loadDevice();
    }

    private void loadDevice(){
        OkHttpUtils.getInstane(token).httpGet(this,Tools.findDeviceByDevBh,"getDevice",new Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
//                Toast.makeText(MainActivity2.this,"拉取设备信息失败",Toast.LENGTH_LONG).show();
                Log.e("dong","拉取设备信息失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    Log.e("dong","getDevice"+response.code());
                    String data = response.body().string();
                    try {
                        JSONObject jo = new JSONObject(data);
                        int code = jo.getInt("code");
                        if(code != 200){
                            Toast.makeText(MainActivity2.this,"拉取设备信息失败",Toast.LENGTH_LONG).show();
                            return;
                        }
                        sharedPreferences.addDevice(MainActivity2.this,jo.getString("data"));
                        String parentId = jo.getJSONObject("data").getString("parentId");
                        initfarm(parentId);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }else{
//                    Toast.makeText(MainActivity2.this,"拉取设备信息接口异常",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    private void uploadDevice(){
        String data = DataSharedPreferences.getInstance().getDevice(MainActivity2.this);
        if(!TextUtils.isEmpty(data)){
            try {
                Device device = Tools.gson.fromJson(data,Device.class);
                HashMap<String, Object> item = device.toHashMap();
//                Log.e("dong","本地设备信息"+Tools.gson.toJson(item));
                OkHttpUtils.getInstane(token).httpPost(MainActivity2.this, Tools.uploadDevice, item, "uploadDevice", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
//                        Toast.makeText(MainActivity2.this,"同步设备信息失败",Toast.LENGTH_LONG).show();
                        Log.e("dong","同步设备信息失败");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(response.isSuccessful()) {
                            String data = response.body().string();
                            Log.e("dong","uploadDevice"+response.code());
//                            Log.e("dong","返回设备信息"+data);
                        }else{
//                            Toast.makeText(MainActivity2.this,"同步设备信息接口异常",Toast.LENGTH_LONG).show();
                        }
                    }
                });
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 加载农场
     * @param parentId
     */
    private void initfarm(String parentId){

        OkHttpUtils.getInstane(token).httpGet(this,Tools.findDeviceFarm+parentId,"getFarm",new Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
//                Toast.makeText(MainActivity2.this,"拉取农场信息失败",Toast.LENGTH_LONG).show();
                Log.e("dong","拉取农场信息失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String data = response.body().string();
                    Log.e("dong","getFarm"+response.code());
                    try {
                        JSONObject jo = new JSONObject(data);
                        int code = jo.getInt("code");
                        if(code != 200){
                            Toast.makeText(MainActivity2.this,"拉取农场信息失败",Toast.LENGTH_LONG).show();
                            return;
                        }
                        sharedPreferences.addFarm(MainActivity2.this,jo.getString("data"));

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //刷新UI
                                if(fragmentList.get(selectIndex) instanceof MainActivity){
                                    ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashString("updateFram");
                                }
                            }
                        });
                    } catch (JSONException e) {
                        //
                    }
                    weather();
                }else{
//                    Toast.makeText(MainActivity2.this,"拉取农场信息接口异常",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * 加载天气
     */
    private void weather(){
        OkHttpUtils.getInstane(token).httpGet(this,Tools.findDeviceWeather+"?currentPage=1&pageSize=7","getWeather",new Callback(){

            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity2.this,"拉取天气信息失败",Toast.LENGTH_LONG).show();
                Log.e("dong","拉取天气信息失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String data = response.body().string();
                    Log.e("dong","getWeather"+response.code());
                    try {
                        Log.e("dong",data);
                        JSONObject jo = new JSONObject(data);
                        int code = jo.getInt("code");
                        if(code != 200){
                            Log.e("dong","拉取天气信息失败");
                            return;
                        }
                        sharedPreferences.addWeather(MainActivity2.this,jo.getString("data"));

                        runOnUiThread(() -> {
                            //刷新UI
                            if(fragmentList.get(selectIndex) instanceof MainActivity){
                                ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashString("updateWeather");
                            }
                        });
                    } catch (JSONException e) {
                        //
                    }
                }else{
//                    Toast.makeText(MainActivity2.this,"拉取天气信息接口异常",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void initService() {
        MyApplication.startService(this);
        bindService(MyApplication.service,serviceConnection,BIND_AUTO_CREATE);
        mqttUtils = MQTTUtils.getInstance(this,devBh,mqttCallback);
    }

    /************************************串口************************************************/
    ISerialAidlInterface iSerialAidlInterface;

    byte funError;

    private IMyAidlCallBack.Stub iMyAidlCallBack = new IMyAidlCallBack.Stub() {
        @Override
        public void onCallback(byte fun,byte[] bytes) throws RemoteException {
            if(bytes != null){
                if(fab.getVisibility() == View.VISIBLE){
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            // 在这里执行需要更新UI的代码
                            fab.setVisibility(View.GONE);
                        }
                    });
                }

                Message msg = mHandler.obtainMessage();
                msg.obj = bytes;
                msg.what = fun;
                mHandler.sendMessage(msg);
            }
        }
        @Override
        public void onCallError(byte fun) throws RemoteException {
            funError = fun;

            if(fab.getVisibility() == View.GONE){
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        // 在这里执行需要更新UI的代码
                        fab.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    };

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iSerialAidlInterface = ISerialAidlInterface.Stub.asInterface(service);
            try {
                iSerialAidlInterface.registerCallback(iMyAidlCallBack, hold.getId());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            iSerialAidlInterface = null;
        }
    };





    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.fab){
            Snackbar.make(v, "串口通信错误："+funError, Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    }



    @Override
    protected void onPause() {
        super.onPause();
        try {
            iSerialAidlInterface.unregisterCallback(iMyAidlCallBack);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
        unbindService(serviceConnection);
    }

    @Override
    protected void onResume() {
        super.onResume();
        bindService(MyApplication.service,serviceConnection,BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        stopService(MyApplication.service);
        if(mqttUtils != null){
            mqttUtils.close();
        }
        if(timer != null){
            timer.cancel();
        }
        if(networkReceiver != null){
            unregisterReceiver(networkReceiver);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    int selectIndex = 0;

    @Override
    public void onPageSelected(int position) {
//        if (fragmentList.get(selectIndex) instanceof OnFragmentInteractionListener) {
//            ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashValues();
//        }
        selectIndex = position;
        if(selectIndex == 7){
            ((OnFragmentInteractionListener) fragmentList.get(selectIndex)).onRefrashValues(hold);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public boolean sendCommand(int fun, int msg,int len, byte[] data) {
        //发送命令
        try {
            iSerialAidlInterface.sendMessage(fun,msg,len,data);
        } catch (RemoteException e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean setHold(Hold hold) {
        try {
            this.hold = hold;
            iSerialAidlInterface.registerCallback(null, hold.getId());
            hold.setId((short) hold.getId());
            sharedPreferences.addHold(MainActivity2.this,hold);
        } catch (RemoteException e) {
            return false;
        }
        return true;
    }


    @Override
    public void startFragment(int page) {
        hisBackPage = selectIndex;
        viewPager.setCurrentItem(page);
    }

    int hisBackPage = 0;

    @Override
    public void bakeFragment() {
        viewPager.setCurrentItem(hisBackPage);
    }

    @Override
    public void setDevice(Device device){
        sharedPreferences.addDevice(MainActivity2.this,Tools.gson.toJson(device));
        //通知服务端

    }
}